import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'

export const useThemeStore = defineStore('theme', () => {
  // 主题状态
  const theme = ref('auto') // 'light', 'dark', 'auto'
  const currentTheme = ref('light') // 当前实际应用的主题
  
  // 从 localStorage 恢复主题设置
  const savedTheme = localStorage.getItem('theme')
  if (savedTheme) {
    theme.value = savedTheme
  }
  
  // 计算当前应该应用的主题
  const effectiveTheme = computed(() => {
    if (theme.value === 'auto') {
      // 自动模式：根据时间判断
      const hour = new Date().getHours()
      return (hour >= 6 && hour < 20) ? 'light' : 'dark'
    }
    return theme.value
  })
  
    // 应用主题到 DOM
  const applyTheme = (themeName) => {
    const root = document.documentElement
    if (themeName === 'dark') {
      root.classList.add('dark-theme')
      root.classList.remove('light-theme')
    } else {
      root.classList.add('light-theme')
      root.classList.remove('dark-theme')
    }
  }
  // 监听主题变化并应用到 DOM
  watch(effectiveTheme, (newTheme) => {
    currentTheme.value = newTheme
    applyTheme(newTheme)
  }, { immediate: true })
  

  
  // 切换主题
  const setTheme = (newTheme) => {
    theme.value = newTheme
    localStorage.setItem('theme', newTheme)
  }
  
  // 切换自动/手动模式
  const toggleAutoMode = () => {
    if (theme.value === 'auto') {
      setTheme('light')
    } else {
      setTheme('auto')
    }
  }
  
  // 手动切换明暗主题
  const toggleManualTheme = () => {
    if (theme.value === 'auto') {
      setTheme('light')
    } else if (theme.value === 'light') {
      setTheme('dark')
    } else {
      setTheme('light')
    }
  }
  
  return {
    theme,
    currentTheme,
    effectiveTheme,
    setTheme,
    toggleAutoMode,
    toggleManualTheme
  }
}) 